/**
 * 远端collection，根据id适配

 state: {
   firstPage: 1,
   lastPage: null,
   currentPage: null,
   pageSize: 25,
   totalPages: null,
   totalRecords: null,
   sortKey: null,
   order: -1
 },
 */
define(['./BaseCollection','underscore'], function(BaseCollection, _) {

  var PARAM_TRIM_RE = /[\s'"]/g;
  var URL_TRIM_RE = /[<>\s'"]/g;
  String.prototype.startsWith = function(s){ return this.slice(0, s.length) == s}
  String.prototype.endsWith   = function(s){ return s == '' || this.slice(-s.length) == s}
  return BaseCollection.extend({
    mode: 'server',
    queryParams:{
      currentPage : "page",
      pageSize : "pageSize",
      totalRecords : "totalRecords"
    },
    state:{
      pageSize:25
    },
    initialize: function(models, options, collection){
      var self = this;
      if (collection) {
        this.id = collection.collection_id;
        this.conditions = _.reduce(collection.conditions,function(conditions, obj){
          var condition = obj.key+obj.operator+obj.value;
          self.queryParams[obj.key] = obj.value;
          return conditions+'&'+condition;
        },'')
      }

      this.listenTo(Backbone,"search",function(e){
          if(e.collection==this){
            return;
          }
          self.queryParams["keyWord"] = e.value;
          self.reset();
          if(this.collection_id){
            self.getFirstPage();
          }
    });
    },

    url: function() {
      if(typeof this.url =="String"&&$.trim(this.url)!=""&&this.url.toLowerCase().startsWith("http://"))
        return this.url+"/"+this.collection_id
      else
        return (window.app.url ? window.app.url : "") + "/api/v2/collections/" + this.collection_id ;
    },
    parseState: function (resp, queryParams, state, options) {
      var records = options.xhr.getResponseHeader("X-totalRecords") || 0;
      return {
              totalRecords: parseInt(records)
            };
    }

  });

});
